import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { ConfigService } from '@nestjs/config';
import { UserLogService } from '../user-log/services/user-log.service';
import { SecurityLogService } from '../security-log/services/security-log.service';

@Injectable()
export class SchedulerService {
  private readonly logger = new Logger(SchedulerService.name);

  constructor(
    private readonly configService: ConfigService,
    private readonly userLogService: UserLogService,
    private readonly securityLogService: SecurityLogService,
  ) {}

  /**
   * 清理用户日志定时任务
   * 每天凌晨2点执行
   */
  @Cron('0 2 * * *')
  async cleanUserLogs() {
    try {
      const retentionDays = this.configService.get<number>('scheduler.userLogRetentionDays', 90);
      const deletedCount = await this.userLogService.cleanOldLogs(retentionDays);
      
      this.logger.log(`定时清理用户日志完成，清理了 ${deletedCount} 条记录，保留天数: ${retentionDays}`);
    } catch (error) {
      this.logger.error('定时清理用户日志失败', error.stack);
    }
  }

  /**
   * 清理安全日志定时任务
   * 每天凌晨2点30分执行
   */
  @Cron('30 2 * * *')
  async cleanSecurityLogs() {
    try {
      const retentionDays = this.configService.get<number>('scheduler.securityLogRetentionDays', 90);
      const deletedCount = await this.securityLogService.cleanOldLogs(retentionDays);
      
      this.logger.log(`定时清理安全日志完成，清理了 ${deletedCount} 条记录，保留天数: ${retentionDays}`);
    } catch (error) {
      this.logger.error('定时清理安全日志失败', error.stack);
    }
  }

  /**
   * 手动清理用户日志
   * @param days 保留天数
   */
  async manualCleanUserLogs(days: number): Promise<number> {
    try {
      const deletedCount = await this.userLogService.cleanOldLogs(days);
      this.logger.log(`手动清理用户日志完成，清理了 ${deletedCount} 条记录，保留天数: ${days}`);
      return deletedCount;
    } catch (error) {
      this.logger.error(`手动清理用户日志失败: ${error.message}`, error.stack);
      throw error;
    }
  }

  /**
   * 手动清理安全日志
   * @param days 保留天数
   */
  async manualCleanSecurityLogs(days: number): Promise<number> {
    try {
      const deletedCount = await this.securityLogService.cleanOldLogs(days);
      this.logger.log(`手动清理安全日志完成，清理了 ${deletedCount} 条记录，保留天数: ${days}`);
      return deletedCount;
    } catch (error) {
      this.logger.error(`手动清理安全日志失败: ${error.message}`, error.stack);
      throw error;
    }
  }

  /**
   * 获取定时任务状态
   */
  getSchedulerStatus() {
    return {
      enabled: this.configService.get<boolean>('scheduler.enabled', true),
      timezone: this.configService.get<string>('scheduler.timezone', 'Asia/Shanghai'),
      userLogRetentionDays: this.configService.get<number>('scheduler.userLogRetentionDays', 90),
      securityLogRetentionDays: this.configService.get<number>('scheduler.securityLogRetentionDays', 90),
      userLogCleanTime: '0 2 * * *', // 每天凌晨2点
      securityLogCleanTime: '30 2 * * *', // 每天凌晨2点30分
    };
  }
}
